<!-- frontend/src/views/About.vue -->

<template>
  <div>
    <h1>学生数据展示</h1>
    <!-- 显示加载状态 -->
    <p v-if="loading">加载中...</p>
    <!-- 显示错误信息 -->
    <p v-if="error" class="error">{{ error }}</p>
    <!-- 显示表格 -->
    <table v-if="!loading && students.length > 0" border="1">
      <thead>
        <tr>
          <th v-for="(header, index) in headers" :key="index">{{ header }}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(student, rowIndex) in students" :key="rowIndex">
          <td v-for="(value, cellIndex) in student" :key="cellIndex">{{ value }}</td>
        </tr>
      </tbody>
    </table>
    <!-- 显示无数据提示 -->
    <p v-if="!loading && students.length === 0">暂无数据</p>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';

// 定义响应式变量
const students = ref([]);
const headers = ref([]);
const loading = ref(true);
const error = ref(null);

onMounted(async () => {
  try {
    // 发起 API 请求
    const response = await axios.get('http://localhost:5000/api/student');
    
    if (response.data.success) {
      students.value = response.data.data;
      
      // 提取表头（假设第一行是表头，但这里数据已经是对象数组）
      if (students.value.length > 0) {
        // 获取所有可能的键作为表头
        const firstStudent = students.value[0];
        headers.value = Object.keys(firstStudent);
      } else {
        headers.value = [];
      }
    } else {
      // 后端返回错误
      error.value = response.data.message || '获取数据失败';
      console.error('后端错误:', response.data.message);
    }
  } catch (err) {
    // 处理网络错误或其他异常
    error.value = err.response?.data?.message || '请求失败，请检查网络连接';
    console.error('请求失败:', err);
  } finally {
    loading.value = false; // 停止加载
  }
});
</script>

<style scoped>
table {
  border-collapse: collapse;
  margin: 20px auto;
  width: 80%;
}
th, td {
  padding: 8px;
  text-align: center;
  border: 1px solid #ddd;
}
th {
  background-color: #f2f2f2;
}
.error {
  color: red;
}
</style>